<template>
  <DefaultLayout>
    <!-- Logo进入动画层 -->
    <div
      v-if="showLogoAnimation"
      ref="logoAnimationLayer"
      class="logo-animation-layer fixed inset-0 z-50 flex items-center justify-center"
    >
      <!-- 白色背景遮罩 -->
      <div ref="whiteMask" class="absolute inset-0 bg-white"></div>

      <!-- 动画Logo -->
      <div ref="animatedLogo" class="relative z-10">
        <img src="/images/nav-logo.svg" alt="UNIGEAR Logo" class="w-32 h-auto" />
      </div>
    </div>

    <!-- 页面内容 -->
    <div class="homepage-container w-full">
      <!-- 第一屏：视频全屏展示 -->
      <section id="hero-video" class="hero-section h-screen relative w-full z-0">
        <!-- 备用背景渐变，如果视频加载失败，将会显示此背景 -->
        <div class="absolute inset-0 bg-gradient-to-br from-blue-500 to-purple-600"></div>

        <video
          ref="heroVideo"
          class="absolute inset-0 w-full h-full object-cover"
          autoplay
          muted
          loop
          playsinline
          aria-label="户外探险场景视频背景"
          role="presentation"
          src="/videos/Video_hero_AFA_D.mp4"
          @error="handleVideoError"
        >
          您的浏览器不支持视频播放
        </video>

        <!-- 视频上的文字层 -->
        <div
          ref="heroContent"
          class="absolute inset-0 flex items-center justify-start z-10 opacity-0"
        >
          <!-- 打字机效果文字区域 -->
          <div class="typewriter-section ml-16 md:ml-24 lg:ml-32">
            <!-- 主标题 -->
            <div class="main-title mb-8">
              <div
                ref="maintitleText"
                class="typewriter-line text-6xl md:text-7xl lg:text-8xl font-black text-orange-500 mb-2"
              >
                PLAY<br />OUTSIDE<br />THE<br />LINES
              </div>
            </div>

            <!-- 副标题 -->
            <div ref="subtitleText" class="subtitle text-lg md:text-xl text-white max-w-lg mb-8">
              The next generation gear feels simple and works like <br />magic.
            </div>
          </div>
        </div>

        <!-- 渐变阴影覆盖层，增强文字可读性 -->
        <div class="absolute inset-0 bg-gradient-to-b from-black/40 to-transparent z-0"></div>

        <!-- 视频播放按钮 (仅在自动播放被阻止时显示) -->
        <div v-if="showPlayButton" class="absolute inset-0 flex items-center justify-center z-20">
          <button
            @click="playVideo"
            class="bg-white/20 backdrop-blur-sm rounded-full p-5 text-white hover:bg-white/30 transition-all"
            aria-label="播放视频"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              class="h-16 w-16"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"
              />
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
          </button>
        </div>

        <!-- 探索系列按钮 - 距离底部更远，与向下指示器保持合适距离 -->
        <div class="absolute bottom-28 z-20 center-with-scrollbar">
          <button
            class="relative overflow-hidden group transform-gpu bg-white text-black px-8 py-3 rounded-md transition-all duration-300 hover:-translate-y-0.5 focus:outline-none focus:ring-2 focus:ring-white focus:ring-opacity-50"
            aria-label="探索我们的产品系列"
          >
            <div class="relative z-10 transition-colors duration-500 group-hover:text-white">
              探索系列
            </div>
            <div
              class="absolute inset-0 transform origin-left scale-x-0 bg-black transition-transform duration-500 ease-out group-hover:scale-x-100"
            ></div>
          </button>
        </div>

        <!-- 向下滚动指示器 - 确保居中对齐 -->
        <div class="absolute bottom-8 z-20 center-with-scrollbar animate-bounce">
          <button
            @click="scrollToNext"
            class="text-white focus:outline-none"
            aria-label="滚动到下一部分"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              class="h-8 w-8"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M19 14l-7 7m0 0l-7-7m7 7V3"
              />
            </svg>
          </button>
        </div>
      </section>

      <!-- 第二屏：产品gif图片展示区域 -->
      <section
        id="product-gif"
        ref="productGifSection"
        class="relative w-full h-screen z-10"
        aria-labelledby="product-gif-heading"
      >
        <!-- 背景GIF图片 -->
        <div class="absolute inset-0">
          <img
            src="/images/quick-open-chair.gif"
            alt="NOMAD OUTDOOR CHAIR 产品展示"
            class="w-full h-full object-cover transition-transform duration-700 ease-out"
            loading="lazy"
          />
          <!-- 背景渐变覆盖层 -->
          <div
            class="absolute inset-0 bg-gradient-to-br from-black/30 via-transparent to-black/40"
          ></div>
        </div>

        <!-- 右上角文字内容 -->
        <div ref="productTitle" class="absolute top-16 right-16 text-white max-w-md z-20">
          <h2 class="text-5xl md:text-6xl font-bold mb-4 leading-tight drop-shadow-lg">
            One handed setup<br />
            and two step installation
          </h2>
        </div>

        <!-- 左下角橙色信息框 -->
        <div ref="productInfoBox" class="absolute bottom-16 left-16 z-20">
          <div class="info-box bg-orange-500 text-black p-8 max-w-sm rounded-sm shadow-2xl">
            <h3 class="text-2xl font-bold mb-4 uppercase tracking-wider">
              NOMAD<br />OUTDOOR CHAIR
            </h3>
            <p class="text-sm mb-6 leading-relaxed font-medium">
              This chair features revolutionary instant-fold technology for quick and easy setup,
              transforming from an ultra-compact size to full-size comfort. Designed to fit
              effortlessly into any backpack.
            </p>
            <div class="mb-6 space-y-1">
              <div class="text-xs font-semibold">• More Ultra-Compact, Easy Setup</div>
              <div class="text-xs font-semibold">• Four Different High-back Support</div>
              <div class="text-xs font-semibold">• Seat Width: 17 in. x 19 inch Size</div>
            </div>
            <button
              class="explore-btn bg-black text-white px-6 py-3 text-sm font-bold uppercase tracking-wide hover:bg-gray-800 transition-colors duration-300 shadow-lg hover:shadow-xl transform hover:-translate-y-0.5"
            >
              EXPLORE
            </button>
          </div>
        </div>
      </section>

      <!-- 第三屏：图片展示区域 -->
      <section
        id="featured-products"
        class="relative py-20 w-full z-10 bg-white"
        aria-labelledby="products-heading"
      >
        <div class="content-container">
          <h2 id="products-heading" class="text-4xl font-bold mb-16 text-center text-gray-900">
            创新设计，卓越品质
          </h2>

          <!-- 大型特色产品图片 -->
          <div class="mb-16 overflow-hidden">
            <div class="relative aspect-video overflow-hidden rounded-lg">
              <div class="absolute inset-0 bg-gradient-to-r from-gray-300 to-gray-400"></div>
              <img
                src="/images/Mask_L_18000.svg"
                alt="特色产品 - 2025年全新户外装备系列"
                class="w-full h-full object-cover transform hover:scale-105 transition duration-700"
                loading="lazy"
                @error="handleImageError"
              />
              <div
                class="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent flex items-end p-8"
              >
                <div class="text-white">
                  <h3 class="text-3xl font-bold mb-2">2025全新系列</h3>
                  <p class="text-lg mb-4">为极端环境打造，科技与设计的完美结合</p>
                  <button
                    class="btn-hover-effect bg-white text-black px-6 py-2 rounded hover:bg-gray-200 transition"
                    aria-label="查看2025全新系列详情"
                  >
                    查看详情
                  </button>
                </div>
              </div>
            </div>
          </div>

          <!-- 产品网格 -->
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 px-4">
            <!-- 产品1 -->
            <div
              class="product-card overflow-hidden rounded-lg shadow-lg transform hover:translate-y-[-10px] transition duration-500"
              role="article"
            >
              <div class="relative h-80">
                <div
                  class="bg-gradient-to-br from-blue-400 to-blue-600 absolute inset-0 flex items-center justify-center text-white text-lg"
                  role="img"
                  aria-label="高山系列背包图片"
                >
                  <span aria-hidden="true">🎒</span> 高山系列背包
                </div>
              </div>
              <div class="p-6 bg-white">
                <h3 class="text-xl font-semibold mb-2">高山系列背包</h3>
                <p class="text-gray-600 mb-4">轻量化设计，40L大容量，防水耐磨，适合长途徒步</p>
                <div class="flex justify-between mb-4">
                  <span class="font-bold text-lg">¥1,299</span>
                  <span class="text-sm text-gray-500 line-through">¥1,599</span>
                </div>
                <button
                  class="btn-hover-effect bg-black text-white px-4 py-2 rounded hover:bg-gray-800 transition w-full"
                  aria-label="购买高山系列背包"
                >
                  立即选购
                </button>
              </div>
            </div>

            <!-- 产品2 -->
            <div
              class="product-card overflow-hidden rounded-lg shadow-lg transform hover:translate-y-[-10px] transition duration-500"
              role="article"
            >
              <div class="relative h-80">
                <div
                  class="bg-gradient-to-br from-green-400 to-green-600 absolute inset-0 flex items-center justify-center text-white text-lg"
                  role="img"
                  aria-label="地形探索者徒步鞋图片"
                >
                  <span aria-hidden="true">👟</span> 地形探索者徒步鞋
                </div>
              </div>
              <div class="p-6 bg-white">
                <h3 class="text-xl font-semibold mb-2">地形探索者徒步鞋</h3>
                <p class="text-gray-600 mb-4">超强抓地力，防水透气，减震鞋底，适合各种野外环境</p>
                <div class="flex justify-between mb-4">
                  <span class="font-bold text-lg">¥899</span>
                  <span class="text-sm text-gray-500 line-through">¥1,099</span>
                </div>
                <button
                  class="btn-hover-effect bg-black text-white px-4 py-2 rounded hover:bg-gray-800 transition w-full"
                  aria-label="购买地形探索者徒步鞋"
                >
                  立即选购
                </button>
              </div>
            </div>

            <!-- 产品3 -->
            <div
              class="product-card overflow-hidden rounded-lg shadow-lg transform hover:translate-y-[-10px] transition duration-500"
              role="article"
            >
              <div class="relative h-80">
                <div
                  class="bg-gradient-to-br from-amber-400 to-amber-600 absolute inset-0 flex items-center justify-center text-white text-lg"
                  role="img"
                  aria-label="全季候帐篷图片"
                >
                  <span aria-hidden="true">⛺</span> 全季候帐篷
                </div>
              </div>
              <div class="p-6 bg-white">
                <h3 class="text-xl font-semibold mb-2">全季候帐篷</h3>
                <p class="text-gray-600 mb-4">防暴雨设计，四季适用，3-4人空间，仅需3分钟快速搭建</p>
                <div class="flex justify-between mb-4">
                  <span class="font-bold text-lg">¥2,499</span>
                  <span class="text-sm text-gray-500 line-through">¥2,899</span>
                </div>
                <button
                  class="btn-hover-effect bg-black text-white px-4 py-2 rounded hover:bg-gray-800 transition w-full"
                  aria-label="购买全季候帐篷"
                >
                  立即选购
                </button>
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>
  </DefaultLayout>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { gsap, ScrollTrigger, SplitText, verifyGSAPGlobal } from '../utils/GSAPGlobalInit.js'
import DefaultLayout from '../layouts/DefaultLayout.vue'

// 响应式数据
const screenHeight = ref(window.innerHeight)
const screenWidth = ref(window.innerWidth)
const showPlayButton = ref(false)
const heroVideo = ref(null)

// 动画相关的引用
const logoAnimationLayer = ref(null)
const whiteMask = ref(null)
const animatedLogo = ref(null)
const heroContent = ref(null)
const showLogoAnimation = ref(true)

// 打字机效果相关引用
const maintitleText = ref(null)
const subtitleText = ref(null)

// 第二屏相关引用
const productGifSection = ref(null)
const productTitle = ref(null)
const productInfoBox = ref(null)

// SplitText实例存储
const splitTextInstances = ref([])
const scrollTriggerInstances = ref([])
let maintitleSplits = null
let subtitleSplit = null

// 初始化SplitText
const initSplitText = () => {
  console.log('🎬 初始化SplitText实例')

  // 为标题元素创建SplitText实例
  if (maintitleText.value) {
    maintitleSplits = new SplitText(maintitleText.value, { type: 'chars' })
    splitTextInstances.value.push(maintitleSplits)

    // 设置初始状态：字符隐藏
    gsap.set(maintitleSplits.chars, {
      opacity: 0,
    })
  }

  // 为副标题创建SplitText实例
  if (subtitleText.value) {
    subtitleSplit = new SplitText(subtitleText.value, { type: 'chars' })
    splitTextInstances.value.push(subtitleSplit)

    // 设置副标题初始状态
    gsap.set(subtitleSplit.chars, {
      opacity: 0,
    })
  }
}

// 开始文字动画 - 逐个字符显示
const startTextAnimation = () => {
  console.log('📝 开始文字动画')

  const tl = gsap.timeline()

  // 动画标题：逐个字符显示
  if (maintitleSplits && maintitleSplits.chars) {
    maintitleSplits.chars.forEach((char, charIndex) => {
      tl.to(
        char,
        {
          opacity: 1,
          y: 0,
          rotationX: 0,
          fontWeight: 700,
          ease: 'back.out(1.7)',
        },
        0.3 + charIndex * 0.13,
      )
    })
  }

  // 副标题动画
  if (subtitleSplit && subtitleSplit.chars) {
    subtitleSplit.chars.forEach((char, index) => {
      tl.to(
        char,
        {
          opacity: 1,
          y: 0,
          duration: 0.4,
          ease: 'power2.out',
        },
        2.85 + index * 0.03,
      )
    })
  }
}

// 初始化第二屏动画
const initProductGifAnimations = () => {
  console.log('🎯 初始化ScrollTrigger动画')

  // 基础检查
  if (!productGifSection.value || !productTitle.value || !productInfoBox.value) {
    console.warn('⚠️ ScrollTrigger: 必要元素未找到')
    return null
  }

  // 清理现有触发器
  ScrollTrigger.getAll().forEach((trigger) => {
    if (trigger.trigger === productGifSection.value) {
      trigger.kill()
    }
  })

  // 设置初始状态
  gsap.set([productTitle.value, productInfoBox.value], {
    opacity: 0,
    y: 50,
  })

  // 创建ScrollTrigger
  try {
    const trigger = ScrollTrigger.create({
      trigger: productGifSection.value,
      start: 'top 80%',
      end: 'bottom 20%',
      markers: true,

      onEnter: () => {
        console.log('ScrollTrigger: 动画开始')
        gsap.to([productTitle.value, productInfoBox.value], {
          opacity: 1,
          y: 0,
          duration: 1,
          stagger: 0.2,
        })
      },

      onLeaveBack: () => {
        console.log('ScrollTrigger: 动画重置')
        gsap.to([productTitle.value, productInfoBox.value], {
          opacity: 0,
          y: 50,
          duration: 0.5,
          stagger: 0.1,
        })
      },
    })

    console.log('✅ ScrollTrigger创建成功')
    return trigger
  } catch (error) {
    console.error('❌ ScrollTrigger创建失败:', error)
    return null
  }
}

// 处理窗口尺寸变化
const handleResize = () => {
  screenHeight.value = window.innerHeight
  screenWidth.value = window.innerWidth
  adjustVideoSize()
}

// Logo进入动画
const playLogoAnimation = () => {
  const tl = gsap.timeline({
    onComplete: () => {
      console.log('🎭 Logo动画完成，隐藏动画层')
      showLogoAnimation.value = false
      setTimeout(() => {
        startTextAnimation()
      }, 100)
    },
  })

  // 设置初始状态
  gsap.set([whiteMask.value, animatedLogo.value], {
    opacity: 1,
  })
  gsap.set(heroContent.value, {
    opacity: 1,
  })

  // 立即触发导航栏准备
  console.log('📡 触发导航栏准备事件')
  window.dispatchEvent(new CustomEvent('prepareNavigation'))

  // Logo动画序列
  tl.to(
    animatedLogo.value,
    {
      y: -window.innerHeight * 0.5,
      duration: 3,
      ease: 'power2.out',
    },
    0,
  )
    .to(
      whiteMask.value,
      {
        opacity: 0,
        duration: 2.5,
        ease: 'power2.out',
      },
      0.5,
    )
    .to(
      heroContent.value,
      {
        opacity: 1,
        duration: 2.5,
        ease: 'power2.out',
      },
      0.5,
    )
    .call(
      () => {
        console.log('📡 2.5秒时触发导航栏显示事件')
        window.dispatchEvent(new CustomEvent('showNavigation'))
      },
      null,
      2.5,
    )
}

// 设置视频
const setupVideo = () => {
  try {
    const video = heroVideo.value
    if (video) {
      video.muted = true
      video.loop = true
      video.playsInline = true

      video.addEventListener('loadeddata', () => {
        adjustVideoSize()
      })

      video.addEventListener('error', (e) => {
        console.error('视频加载错误:', e)
      })

      setTimeout(() => {
        video.play().catch((error) => {
          console.log('视频自动播放被阻止', error)
          showPlayButton.value = true
        })
      }, 500)
    }
  } catch (error) {
    console.error('设置视频时发生错误:', error)
  }
}

// 调整视频尺寸
const adjustVideoSize = () => {
  const video = heroVideo.value
  if (!video) return

  try {
    const videoRatio = 16 / 9
    const screenRatio = screenWidth.value / screenHeight.value

    if (screenRatio < videoRatio) {
      video.classList.add('height-full')
      video.classList.remove('width-full')
    } else {
      video.classList.add('width-full')
      video.classList.remove('height-full')
    }
  } catch (error) {
    console.error('调整视频尺寸错误:', error)
  }
}

// 滚动到下一部分
const scrollToNext = () => {
  const targetSection = document.getElementById('product-gif')
  if (targetSection) {
    targetSection.scrollIntoView({
      behavior: 'smooth',
      block: 'start',
    })
  }
}

// 手动播放视频
const playVideo = () => {
  try {
    const video = heroVideo.value
    if (video) {
      video.muted = true
      video
        .play()
        .then(() => {
          showPlayButton.value = false
        })
        .catch((error) => {
          console.error('手动播放视频失败:', error)
        })
    }
  } catch (error) {
    console.error('播放视频时发生错误:', error)
  }
}

// 处理视频加载错误
const handleVideoError = (event) => {
  console.error('视频加载失败:', event)
  showPlayButton.value = false
  const video = event.target
  if (video) {
    video.style.display = 'none'
  }
}

// 处理图片加载错误
const handleImageError = (event) => {
  console.error('图片加载失败:', event)
  const img = event.target
  if (img) {
    const parent = img.parentElement
    if (parent) {
      const textDiv = document.createElement('div')
      textDiv.className =
        'absolute inset-0 flex items-center justify-center text-white text-xl font-bold'
      textDiv.textContent = '产品图片'
      parent.appendChild(textDiv)
      img.style.opacity = '0'
    }
  }
}

// 生命周期钩子
onMounted(() => {
  console.log('🚀 HomePage组件已挂载')

  // 验证GSAP全局状态
  const gsapReady = verifyGSAPGlobal()
  if (!gsapReady) {
    console.error('❌ GSAP全局验证失败，ScrollTrigger可能无法正常工作')
  }

  window.addEventListener('resize', handleResize)
  handleResize()
  setupVideo()
  initSplitText()

  // 使用nextTick确保DOM完全渲染
  nextTick(() => {
    // 确保GSAP和ScrollTrigger完全初始化
    if (typeof window.gsap === 'undefined' || typeof window.ScrollTrigger === 'undefined') {
      window.gsap = gsap
      window.ScrollTrigger = ScrollTrigger
      console.log('🔧 已修复GSAP和ScrollTrigger的全局引用')
    }

    // 等待页面完全稳定后初始化ScrollTrigger
    setTimeout(async () => {
      // 确保所有元素都已渲染
      if (!productGifSection.value) {
        console.error('❌ productGifSection.value为空，延迟重试')
        setTimeout(() => {
          if (productGifSection.value) {
            const scrollTriggerInstance = initProductGifAnimations()
            if (scrollTriggerInstance) {
              scrollTriggerInstances.value.push(scrollTriggerInstance)
            }
          }
        }, 500)
        return
      }

      try {
        const scrollTriggerInstance = initProductGifAnimations()
        if (scrollTriggerInstance) {
          scrollTriggerInstances.value.push(scrollTriggerInstance)

          // 监听窗口大小变化
          const handleResizeRefresh = () => {
            setTimeout(() => {
              ScrollTrigger.refresh()
            }, 100)
          }

          window.addEventListener('resize', handleResizeRefresh)

          // 添加清理函数
          scrollTriggerInstance._cleanup = () => {
            window.removeEventListener('resize', handleResizeRefresh)
          }

          // 验证ScrollTrigger是否正确创建
          setTimeout(() => {
            const allTriggers = ScrollTrigger.getAll()
            console.log('✅ ScrollTrigger初始化完成:', allTriggers.length, '个触发器')

            // 修复标记定位
            setTimeout(() => {
              ScrollTrigger.refresh()
            }, 100)
          }, 200)
        } else {
          console.error('❌ ScrollTrigger实例创建失败')
        }
      } catch (error) {
        console.error('❌ ScrollTrigger初始化异常:', error)
      }
    }, 1000)
  })

  // 页面加载完成后开始Logo动画
  setTimeout(() => {
    playLogoAnimation()
  }, 300)
})

onBeforeUnmount(() => {
  console.log('🧹 清理HomePage组件')

  window.removeEventListener('resize', handleResize)

  // 清理SplitText实例
  splitTextInstances.value.forEach((split) => {
    if (split && split.revert) {
      split.revert()
    }
  })

  // 清理ScrollTrigger实例
  scrollTriggerInstances.value.forEach((trigger) => {
    if (trigger) {
      if (trigger._cleanup && typeof trigger._cleanup === 'function') {
        trigger._cleanup()
      }
      if (trigger.kill) {
        trigger.kill()
      }
    }
  })

  // 清理所有剩余的ScrollTrigger实例
  ScrollTrigger.getAll().forEach((trigger) => trigger.kill())
})
</script>

<style scoped>
/* 页面容器样式 */
.homepage-container {
  background: white;
}

/* 信息框动画效果 */
.info-box {
  position: relative;
  overflow: hidden;
}

.explore-btn {
  position: relative;
  overflow: hidden;
}

/* 居中对齐工具类 */
.center-with-scrollbar {
  left: 50%;
  transform: translateX(-50%);
}
</style>
